<template>
  <t-card :bordered="false">

    <!-- 自定义表格 -->
    <t-table 
      row-key="index" 
      :data="tableData"  
      size="small"
      stripe 
      bordered 
      :columns="columns">
      <template #completeTime="{ row }">
        {{ row.completeTime ? dayjs(row.completeTime).format('YYYY-MM-DD HH:mm:ss') : '' }}
      </template>
      <template #operation="{ row }">
        <t-space break-line>
          <t-popconfirm content="确认要确认完成该项吗？"
            v-if="row.value != '1'"
            @confirm="handleConfirmComplete({ name: row.name, id: orderDetails.id, orderId: orderDetails.orderId, progressType: row.value })">
            <t-link theme="primary" v-permission="['system:single-product-contract:update-progress']" v-if="!row.completeTime"> 确认完成 </t-link>
          </t-popconfirm>
          <t-popconfirm content="确认要确认完成该项吗？"
            v-else
            @confirm="handleConfirmComplete({ name: row.name, id: orderDetails.id, orderId: orderDetails.orderId, progressType: row.value })">
            <t-link theme="primary" v-permission="['system:single-product-contract:update-progress']" v-if="!contractDetails.placeAnOrderStatus&&!contractDetails.placeAnOrderTime"> 确认完成 </t-link>
          </t-popconfirm>
          <t-popconfirm content="确认要同意下单吗？"
            v-if="contractDetails.placeAnOrderStatus == '1'&&row.value=='1'"
            @confirm="handleApproveSingle({ name: row.name, orderId: orderDetails.orderId, result: 2 })">
            <t-link theme="primary" v-permission="['system:single-product-contract:approval-place-an-order']"> 同意 </t-link>
          </t-popconfirm>
          <t-popconfirm content="确认要驳回下单吗？"
            v-if="contractDetails.placeAnOrderStatus == '1'&&row.value=='1'"
            @confirm="handleApproveSingle({ name: row.name, orderId: orderDetails.orderId, result: 3 })">
            <t-link theme="danger" v-permission="['system:single-product-contract:approval-place-an-order']"> 驳回 </t-link>
          </t-popconfirm>
        </t-space>
      </template>
    </t-table>


  </t-card>
</template>


<script setup lang="ts">
import dayjs from 'dayjs';
import { MessagePlugin, TableCol } from 'tdesign-vue-next';
import { inject, onMounted, Ref, ref, useTemplateRef } from 'vue';

import { singleProductContractApproval, singleProductContractCRUD, updateSingleProductContractProgress } from '@/api/order/single'
import CustomTable from '@/components/custom/table/index.vue';
import { useDictionaryStore } from '@/store';

// 字典仓库
const dictionaryStore = useDictionaryStore();
// 产品详情
const orderDetails = inject<Ref<Record<string, any>>>('orderDetails');

// columns
const columns: TableCol[] = [
  { colKey: 'name', title: '进度名称' },
  { colKey: 'completeTime', title: '完成时间' },
  { colKey: 'operation', title: '操作', fixed: 'right' },
].map(column => ({ ...column, align: 'center' }));

const tableData = ref([])

// 合同详情
const contractDetails = ref<Record<string, any>>({});
// 处理获取合同详情
const handleGetContractDetails = () => {
  const params = {
    orderId: orderDetails.value.orderId,
  };
  singleProductContractCRUD.page(params)
    .then((data) => {
      if (data.total > 0) {
        contractDetails.value = data.list[0]
        tableData.value = dictionaryStore.get('single_product_process').map((item, index) => {
          let completeTime = '';
          switch (item.value) {
            case '1': // 下单
              completeTime = contractDetails.value.placeAnOrderTime;
              break;
            case '2': // 送柜子
              completeTime = contractDetails.value.songGuiziTime;
              break;
            case '3': // 验收
              completeTime = contractDetails.value.acceptanceCheckTime;
              break;
            default:
              completeTime = '';
          }
          return {
            index, // 唯一标识
            name: item.label, // 进度名称
            completeTime,     // 完成时间
            value: item.value,
            id: contractDetails.value.id
          };
        })
      } else {
        contractDetails.value = {}
      }
    })
    .catch(({ message }) => {
      MessagePlugin.error(message);
    }).finally(()=> {
      console.log(tableData.value,'tableData');
      
    })

};
onMounted(() => {
  handleGetContractDetails()
});

// 处理确认完成
const handleConfirmComplete = (params: Record<string, any>) => {
  const { name, ...rest } = params;
  updateSingleProductContractProgress({ ...rest })
    .then(() => {
      MessagePlugin.success(`${params.name}确认完成`);
      handleGetContractDetails()
    })
    .catch(({ message }) => {
      MessagePlugin.error(message);
    });
};
// 处理确认完成
const handleApproveSingle = (params: Record<string, any>) => {
  const { name, ...rest } = params;
  singleProductContractApproval({ ...rest })
    .then(() => {
       MessagePlugin.success(`${params.result==2?'同意':'驳回'}${params.name}成功`);
      handleGetContractDetails()
    })
    .catch(({ message }) => {
      MessagePlugin.error(message);
    });
};

</script>
